package com.ruoyi.business.controller;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.business.domain.ClassInfo;
import com.ruoyi.business.domain.School;
import com.ruoyi.business.domain.User;
import com.ruoyi.business.domain.dto.StudentDTO;
import com.ruoyi.business.domain.vo.BindingExcelVO;
import com.ruoyi.business.service.IUserService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.business.domain.Binding;
import com.ruoyi.business.service.IBindingService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 学生绑定Controller
 * 
 * @author lcz
 * @date 2025-03-31
 */
@Api(tags = "学校学生绑定相关接口")
@RestController
@RequestMapping("/business/binding")
public class BindingController extends BaseController
{
    @Autowired
    private IBindingService bindingService;
    @Autowired
    private IUserService userService;

    /**
     * 查询学生绑定列表
     */
    @ApiOperation(value = "后台----查询学生绑定列表")
//    @PreAuthorize("@ss.hasPermi('business:binding:list')")
    @GetMapping("/list")
    public TableDataInfo list(Binding binding)
    {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (!ObjectUtils.isEmpty(sysUser.getSchoolId())){
            binding.setSchoolId(sysUser.getSchoolId());
        }
        startPage();
        List<Binding> list = bindingService.selectBindingList(binding);
        return getDataTable(list);
    }

    /**
     * 导出学生绑定列表
     */
    @ApiOperation(value = "后台----导出学生绑定列表")
//    @PreAuthorize("@ss.hasPermi('business:binding:export')")
    @Log(title = "学生绑定", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Binding binding)
    {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (!ObjectUtils.isEmpty(sysUser.getSchoolId())){
            binding.setSchoolId(sysUser.getSchoolId());
        }
        List<Binding> list = bindingService.selectBindingList(binding);
        List<BindingExcelVO> temp = JSON.parseArray(JSON.toJSONString(list), BindingExcelVO.class);
        ExcelUtil<BindingExcelVO> util = new ExcelUtil<BindingExcelVO>(BindingExcelVO.class);
        util.exportExcel(response, temp, "学生绑定数据");
    }

    /**
     * 获取学生绑定详细信息
     */
    @ApiOperation(value = "后台----获取学生绑定详细信息")
//    @PreAuthorize("@ss.hasPermi('business:binding:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(bindingService.selectBindingById(id));
    }

    /**
     * 新增学生绑定
     */
    @ApiOperation(value = "后台----新增学生绑定")
//    @PreAuthorize("@ss.hasPermi('business:binding:add')")
    @Log(title = "学生绑定", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Binding binding)
    {
        return toAjax(bindingService.insertBinding(binding));
    }

    /**
     * 修改学生绑定
     */
    @ApiOperation(value = "后台----修改学生绑定")
//    @PreAuthorize("@ss.hasPermi('business:binding:edit')")
    @Log(title = "学生绑定", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Binding binding)
    {
        return toAjax(bindingService.updateBinding(binding));
    }

    /**
     * 删除学生绑定
     */
    @ApiOperation(value = "后台----删除学生绑定")
//    @PreAuthorize("@ss.hasPermi('business:binding:remove')")
    @Log(title = "学生绑定", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(bindingService.deleteBindingByIds(ids));
    }

    /**
     * 导入接口
     */
    @ApiOperation("后台----导入绑定数据")
    @PostMapping("/importBindingData")
    public AjaxResult importBindingData(MultipartFile file) throws Exception {

        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (ObjectUtils.isEmpty(sysUser.getSchoolId())) {
            return AjaxResult.error("该账号不属于任何学校，无法导入学生信息");
        }

        InputStream inputStream = file.getInputStream();
        ExcelUtil<BindingExcelVO> util = new ExcelUtil<BindingExcelVO>(BindingExcelVO.class);
        List<BindingExcelVO> bindingExcelVOList = util.importExcel(inputStream);

        Binding param = new Binding();
        param.setSchoolId(sysUser.getSchoolId());
        List<Binding> dataList = bindingService.selectBindingList(param);
        //TODO: 比较两个列表，找出bindingExcelVOList中有多少数据是dataList中存在的，并返回这些数据的行号

        // 用于存储重复数据的行号
        List<Integer> duplicateRowNumbers = new ArrayList<>();

        try{
            // 创建一个映射，用于快速查找dataList中是否存在相同的键
            Map<String, Binding> accountMap = dataList.stream()
                    .collect(Collectors.toMap(
                            binding -> binding.getAccount(),
                            binding -> binding
                    ));

            Map<String, Binding> codeMap = dataList.stream()
                    .collect(Collectors.toMap(
                            binding -> binding.getCode(),
                            binding -> binding
                    ));

            // 遍历导入的bindingExcelVOList，检查是否存在重复数据
            for (int i = 0; i < bindingExcelVOList.size(); i++) {
                BindingExcelVO studentDTO = bindingExcelVOList.get(i);
                String account = studentDTO.getAccount();
                String code = studentDTO.getCode();
                if (accountMap.containsKey(account)) {
                    // 如果存在重复，记录行号（注意：Excel行号从1开始，i从0开始，所以需要加2）
                    duplicateRowNumbers.add(i + 2); // 假设第一行为标题行
                    continue;
                }
                if (codeMap.containsKey(code)) {
                    // 如果存在重复，记录行号（注意：Excel行号从1开始，i从0开始，所以需要加2）
                    duplicateRowNumbers.add(i + 2); // 假设第一行为标题行
                    continue;
                }
            }
        }catch (Exception e){
            return AjaxResult.error("导入失败,请检查:学号、账号、手机号 是否为正确值");
        }

        // 如果有重复数据，返回错误信息和重复的行号
        if (!duplicateRowNumbers.isEmpty()) {
            return AjaxResult.error("以下行号的数据已存在：" + duplicateRowNumbers.toString());
        }

        List<Binding> bindingList = JSON.parseArray(JSON.toJSONString(bindingExcelVOList), Binding.class);

        if (bindingList.size() > 0){
            for (Binding binding : bindingList){
                binding.setSchoolId(sysUser.getSchoolId());
                binding.setCreateTime(new Date());
                User userParam = new User();
                userParam.setSchoolId(sysUser.getSchoolId());
                userParam.setAccount(binding.getAccount());
                List<User> userList = userService.selectUserList(userParam);
                if (userList.size()<=0){
                    return AjaxResult.error("导入失败，系统中不存在账号为"+binding.getAccount()+"的学生");
                }
                binding.setStudentName(userList.get(0).getUserName());
                binding.setUserId(userList.get(0).getId());
            }
            bindingService.batchInsertBinding(bindingList);
        }
        return AjaxResult.success();
    }

    /** 前端接口 ***************************************************************************************************/
    /** 前端接口 ***************************************************************************************************/
    /** 前端接口 ***************************************************************************************************/

    /**
     * 查询学生绑定列表
     * 接口路径：/binding/front/list
     */
    @GetMapping("/front/list")
    @ApiOperation("前台查询学生绑定列表")
    public TableDataInfo<Binding> frontList(Binding binding)
    {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (!ObjectUtils.isEmpty(sysUser.getSchoolId())){
            binding.setSchoolId(sysUser.getSchoolId());
        }
        startPage();
        List<Binding> list = bindingService.selectBindingList(binding);
        return getDataTable(list);
    }

//    /**
//     * 获取学生绑定详细信息
//     * 接口路径：/binding/front/info
//     */
//    @ApiOperation("前台获取学生绑定详细信息")
//    @GetMapping(value = "/front/info")
//    public R<Binding> frontInfo(@RequestParam("id") Long id)
//    {
//        return R.ok(bindingService.selectBindingById(id));
//    }
//
//    /**
//     * 新增学生绑定
//     * 接口路径：/binding/front/add
//     */
//    @ApiOperation("前台新增学生绑定")
//    @PostMapping("/front/add")
//    public AjaxResult frontAdd(@RequestBody Binding binding)
//    {
//        return toAjax(bindingService.insertBinding(binding));
//    }
//
//    /**
//     * 修改学生绑定
//     * 接口路径：/binding/front/edit
//     */
//    @ApiOperation("前台修改学生绑定")
//    @PostMapping("/front/edit")
//    public AjaxResult frontEdit(@RequestBody Binding binding)
//    {
//        return toAjax(bindingService.updateBinding(binding));
//    }
//
//    /**
//     * 删除学生绑定
//     * 接口路径：/binding/front/delete
//     */
//    @ApiOperation("前台删除学生绑定")
//    @GetMapping("/front/delete")
//    public AjaxResult frontRemove(@RequestParam Long[] ids)
//    {
//        return toAjax(bindingService.deleteBindingByIds(ids));
//    }
}
